﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>出库单管理</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        .container {
            width: 95%;
            height: 900px;
            margin: 20px auto;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .search-area {
            margin-bottom: 16px;
        }

        .btn-group {
            margin-bottom: 16px;
        }

        .custom-select,
        .el-input {
            width: 150px !important;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form inline>
                <el-form-item label="出库单号">
                    <el-input v-model="Form.outOrderNo" placeholder="请输入出库单号"></el-input>
                </el-form-item>
                <el-form-item label="出库类型">
                    <el-select v-model="Form.outType" placeholder="请选择" class="custom-select">
                        <el-option v-for="item in industryOptions"
                                   :key="item.dictValue"
                                   :label="item.dictLabel"
                                   :value="item.dictLabel">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单据状态">
                    <el-select v-model="Form.orderStatus" placeholder="请选择" class="custom-select">
                        <el-option v-for="item in industryOptions2" :key="item.dictValue"
                                   :label="item.dictLabel" :value="item.dictValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称">
                    <el-select v-model="Form.warehouseName" placeholder="请选择" class="custom-select">
                        <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadData">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button v-on:click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区域 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="goToAddPage">新增</el-button>
            <el-button v-on:click="handleDelete">删除</el-button>
            <el-button>复制</el-button>
            <el-button v-on:click="handleAudit">审核</el-button>
            <el-button>撤销</el-button>
            <el-button>关闭</el-button>
            <el-button>开启</el-button>
            <el-button>导出</el-button>
            <el-button>刷新</el-button>
        </div>

        <!-- 数据表格区域（关键：prop已对照DTO修改） -->
        <el-table :data="tableData" border style="width: 100%" ref="outOrderTable">
            <el-table-column type="selection" width="55"></el-table-column>
            <!-- 出库单号：DTO→outbound_order_no -->
            <el-table-column prop="outbound_order_no" label="出库单号" fixed="left" width="170">
                <template #default="scope">
                    <span style="color: #409EFF; cursor: pointer;" v-on:click="gotoDetail(scope.row.outbound_order_no)">
                        {{ scope.row.outbound_order_no }}
                    </span>
                </template>
            </el-table-column>
            <!-- 出库类型：DTO→dictLabel -->
            <el-table-column prop="dictLabel" label="出库类型" fixed="left" width="100"></el-table-column>
            <!-- 单据状态：DTO→outbound_status -->
            <el-table-column prop="outbound_status" label="状态" fixed="left" width="100">
                <template #default="scope">
                    {{ formatDocumentStatus(scope.row.outbound_status) }}
                </template>
            </el-table-column>
            <!-- 出库日期：DTO→date_of_shipment -->
            <el-table-column prop="date_of_shipment" label="出库日期" width="120">
                <template #default="scope">
                    {{ formatDate(scope.row.date_of_shipment) }}
                </template>
            </el-table-column>
            <!-- 仓库名称：DTO→warehouse_name -->
            <el-table-column prop="warehouse_name" label="仓库名称" width="120"></el-table-column>
            <!-- 关联单号：DTO→associated_order_no -->
            <el-table-column prop="associated_order_no" label="关联单号" width="170"></el-table-column>
            <!-- 客户名称：DTO→customer_name -->
            <el-table-column prop="customer_name" label="客户名称" width="120"></el-table-column>
            <!-- 联系人：DTO→contact_person -->
            <el-table-column prop="contact_person" label="联系人" width="100"></el-table-column>
            <!-- 联系方式：DTO→contact_phone_number -->
            <el-table-column prop="contact_phone_number" label="联系方式" width="120"></el-table-column>
            <!-- 出库货品：DTO→product_name -->
            <el-table-column prop="product_name" label="出库货品" width="150"></el-table-column>
            <!-- 出库数量：DTO→curr_stk_out_num -->
            <el-table-column prop="curr_stk_out_num" label="出库数量" width="100"></el-table-column>
            <!-- 出库金额：DTO→saleamount -->
            <el-table-column prop="saleamount" label="出库金额" width="100"></el-table-column>
            <!-- 经办人：DTO→handler_user_name -->
            <el-table-column prop="handler_user_name" label="经办人" width="100"></el-table-column>
            <!-- 制单人：DTO→creator_user_name -->
            <el-table-column prop="creator_user_name" label="制单人" width="120"></el-table-column>
            <!-- 所在部门：DTO→organization_name -->
            <el-table-column prop="organization_name" label="所在部门" width="100"></el-table-column>
            <!-- 制单时间：DTO→create_time -->
            <el-table-column prop="create_time" label="制单时间" width="180">
                <template #default="scope">
                    {{ formatDateTime(scope.row.create_time) }}
                </template>
            </el-table-column>
            <!-- 审核人：DTO→approver_user_name -->
            <el-table-column prop="approver_user_name" label="审核人" width="170"></el-table-column>
            <!-- 审核时间：DTO→update_time -->
            <!-- 审核时间列：添加空值判断 -->
            <el-table-column prop="update_time" label="审核时间" width="170">
                <template #default="scope">
                    {{ scope.row.update_time ? formatDateTime(scope.row.update_time) : '-' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
                <template #default="scope">
                    <el-button-group>
                        <el-button type="text" v-on:click="goToEdit(scope.row.outbound_order_no)">编辑</el-button>
                        <el-button type="text" style="color: red; margin-left: 10px;" v-on:click="handleSingleDelete(scope.row.outbound_order_no, scope.row)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>



        <!-- 审核弹窗 -->
        <el-dialog v-model="auditDialogVisible" title="审核" width="30%">

                <el-form-item label="审核结果">
                    <el-radio-group v-model="auditForm.result">
                        <el-radio label="1">通过</el-radio>
                        <el-radio label="0">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核意见">
                    <el-input v-model="auditForm.opinion" type="textarea" rows="4"></el-input>
                </el-form-item>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click ="auditDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click ="submitAudit">确定</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 分页组件 -->
        <el-pagination v-on:size-change="handleSizeChange"
                       v-on:current-change="handleCurrentChange"
                       :current-page="pageIndex"
                       :page-sizes="[10, 20, 30, 40]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="totalCount"
                       style="margin-top: 16px;">
        </el-pagination>

    </div>

    <script>
        const { createApp, onMounted, reactive, ref } = Vue;
        const app = createApp({
            setup() {
                const tableData = ref([]);
                const totalCount = ref(0);
                const pageIndex = ref(1);
                const pageSize = ref(10);

                const Form = reactive({
                    outOrderNo: '',
                    outType: '',
                    orderStatus: '',
                    warehouseName: '',
                });

                // 分页大小变更
                const handleSizeChange = (newSize) => {
                    pageSize.value = newSize;
                    loadData();
                };

                // 当前页变更
                const handleCurrentChange = (newPage) => {
                    pageIndex.value = newPage;
                    loadData();
                };

                // 重置查询条件
                const resetSearch = () => {
                    Form.outOrderNo = '';
                    Form.outType = '';
                    Form.orderStatus = '';
                    Form.warehouseName = '';
                    pageIndex.value = 1;
                    loadData();
                };

                // 加载分页数据（已适配DTO返回格式）
                const loadData = async () => {
                    try {
                        const response = await axios.get('/OutboundManagement/GetPagedOutboundOrders', {
                            params: {
                                outboundOrderNo: Form.outOrderNo,
                                outboundType: Form.outType,
                                outboundStatus: Form.orderStatus,
                                warehouseName: Form.warehouseName,
                                currentPage: pageIndex.value,
                                pageSize: pageSize.value
                            }
                        });
                        if (response.data && response.data.success) { // 适配后端{success, data, total}格式
                            tableData.value = response.data.data; // 后端data字段对应DTO列表
                            totalCount.value = response.data.total; // 后端total字段对应总条数
                        }
                    } catch (error) {
                        console.error('加载数据失败：', error);
                        ElementPlus.ElMessage.error('加载数据失败，请稍后再试');
                    }
                };

             

              // 单据状态数字转中文映射
                const formatDocumentStatus = (status) => {
                    const statusMap = {
                        '1': '草稿',
                        '2': '待审核',
                        '3': '驳回',
                        '4': '已完成',
                        '5': '未入库',
                        '6': '未出库',
                        '7': '部分出库',
                        '8': '部分入库'
                    };
                    return statusMap[status] || '未知状态';
                };

                // 跳转到详情页（参数用DTO的outbound_order_no）
                const gotoDetail = (outOrderNo) => {
                    console.log('跳转出库单详情页面，单号：', outOrderNo);
                };

                // 跳转到编辑页（参数用DTO的outbound_order_no）
                const goToEdit = (outOrderNo) => {
                    console.log('跳转出库单编辑页面，单号：', outOrderNo);
                };

                // 单条删除（参数用DTO的outbound_order_no）
                const handleSingleDelete = (outOrderNo, row) => {
                    ElementPlus.ElMessageBox.confirm(
                        '此操作将逻辑删除该出库单，是否继续？',
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(async () => {
                        try {
                            if (outOrderTable.value) {
                                outOrderTable.value.toggleRowSelection(row, false);
                            }
                            ElementPlus.ElMessage.success('删除成功（仅前端模拟）');
                            loadData();
                        } catch (err) {
                            ElementPlus.ElMessage.error('删除失败（仅前端模拟）');
                        }
                    }).catch(() => {
                        ElementPlus.ElMessage.info('已取消删除');
                    });
                };

                // 批量删除
                const handleDelete = () => {
                    if (!outOrderTable.value) {
                        ElementPlus.ElMessage.warning('表格未加载完成，请稍后再试');
                        return;
                    }

                    const selectedRows = outOrderTable.value.getSelectionRows();

                    if (selectedRows.length === 0) {
                        ElementPlus.ElMessage.warning('请勾选需要删除的单据！');
                        return;
                    }

                    ElementPlus.ElMessageBox.confirm(
                        '此操作将逻辑删除选中的出库单，是否继续？',
                        '提示',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    ).then(async () => {
                        try {
                            ElementPlus.ElMessage.success('批量删除成功（仅前端模拟）');
                            loadData();
                        } catch (err) {
                            ElementPlus.ElMessage.error('批量删除失败（仅前端模拟）');
                        }
                    }).catch(() => {
                        ElementPlus.ElMessage.info('已取消删除');
                    });
                };



                // 日期格式化（精确到年月日：YYYY-MM-DD）
                const formatDate = (dateStr) => {
                    if (!dateStr) return '';
                    const date = new Date(dateStr);
                    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                };

                      const formatDateTime = (dateStr) => {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            // 若为默认空值（如0001-01-01），直接返回空
            if (date.getFullYear() === 1) return '';
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
        };


                   const industryOptions = ref([]);
                  const getIndustryDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/StockoutType');
                        industryOptions.value = response.data;
                    } catch (error) {
                        console.error('获取出库类型字典失败：', error);
                        ElementPlus.ElMessage.error('获取出库类型数据失败');
                    }
                };


                    // 下拉框选项
                const warehouseOptions = ref([]);
                    // 其他基础逻辑
                const loadWarehouseOptions = async () => {
                    try {
                        const res = await axios.get('/OutboundManagement/GetAllWarehouses');
                        if (!res.data.success) {
                            ElementPlus.ElMessage.error(res.data.message || '查询仓库失败');
                            return;
                        }
                        warehouseOptions.value = res.data.data.map(item => ({
                            label: item.warehouse_name,
                            value: item.warehouse_id.toString()
                        }));
                    } catch (error) {
                        console.error('加载仓库列表网络错误:', error);
                        ElementPlus.ElMessage.error('网络异常，无法加载仓库数据');
                    }
                };



                 const industryOptions2 = ref([]); //单据状态

              // 3. 获取后端字典数据单据状态
                const getIndustryDict2 = async () => {
                    try {

                        const response = await axios.get('/api/Dict/datas/StockOrderStatus');
                        console.log(response.data);
                        industryOptions2.value = response.data || [];
                        console.log('获取单据状态成功:', industryOptions2.value);
                    } catch (error) {
                        console.error('获取单据状态失败：', error);
                        ElementPlus.ElMessage.error('单据状态数据加载失败');
                    }
                };



                        const auditDialogVisible = ref(false); // 审核弹窗显隐
                        const auditForm = reactive({
                          result: '', // 默认审核结果
                          opinion: ''     // 审核意见
                        });
                        const selectedOutOrderNos = ref([]); // 选中的出库单号列表

                        // 点击“审核”按钮：获取选中行并打开弹窗
                        const handleAudit = () => {
                          const selectedRows = outOrderTable.value.getSelectionRows();
                          if (selectedRows.length === 0) {
                            ElementPlus.ElMessage.warning('请勾选需要审核的出库单！');
                            return;
                          }
                          selectedOutOrderNos.value = selectedRows.map(row => row.outbound_order_no);
                          auditDialogVisible.value = true;
                        };

                               // 提交审核请求（修改后）
        const submitAudit = async () => {
          try {
            // 1. 校验必填项
            if (!auditForm.result) {
              ElementPlus.ElMessage.warning('请选择审核结果');
              return;
            }
            if (!auditForm.opinion) {
              ElementPlus.ElMessage.warning('请输入审核意见');
              return;
            }

            // 2. 转换参数：前端result（1/0）→ 后端audit_result（通过/驳回）
            const auditResult = auditForm.result === '1' ? '通过' : '驳回';

            // 3. 获取当前登录用户（假设前端从localStorage存储，根据实际项目调整）
            const reviewer = localStorage.getItem('userName') || 'admin';

            // 4. 提交请求（参数名与后端OutboundAuditDTO完全一致）
            const response = await axios.post('/OutboundManagement/AuditOutboundOrders', {
              ordernos: selectedOutOrderNos.value, // 对应DTO的ordernos（出库单号列表）
              audit_result: auditForm.result,           // 对应DTO的audit_result（通过/驳回）
              audit_opinion: auditForm.opinion,    // 对应DTO的audit_opinion（审核意见）
              reviewer: reviewer                   // 对应DTO的reviewer（审核人）
            }, {
              headers: { 'Content-Type': 'application/json' } // 明确JSON格式
            });

            // 5. 处理响应（假设后端返回 { success: boolean, message: string }）
            if (response.data.success) {
              ElementPlus.ElMessage.success('审核成功！');
              auditDialogVisible.value = false;
              loadData(); // 刷新出库单列表
              // 重置审核表单
              auditForm.result = '';
              auditForm.opinion = '';
            } else {
              ElementPlus.ElMessage.error(`审核失败：${response.data.message}`);
            }
          } catch (error) {
            console.error('审核请求异常：', error);
            ElementPlus.ElMessage.error(`审核失败：${error.response?.data?.message || '网络异常'}`);
          }
        };




                // 跳转到新增页
                const goToAddPage = () => {
                    window.location.href = '/OutboundManagement/Add';
                };

                // 表格Ref
                const outOrderTable = ref(null);

                onMounted(() => {
                    loadData();
                    getIndustryDict();
                    loadWarehouseOptions();
                    getIndustryDict2();
                });

                return {
                    tableData,
                    totalCount,
                    pageIndex,
                    pageSize,
                    loadData,
                    handleSizeChange,
                    handleCurrentChange,
                    resetSearch,
                    goToAddPage,
                    Form,
                    gotoDetail,
                    goToEdit,
                    handleSingleDelete,
                    handleDelete,
                    formatDate,
                    formatDateTime,
                    formatDocumentStatus,
                    outOrderTable,
                    industryOptions,
                    warehouseOptions,
                    industryOptions2,

                    auditDialogVisible,
                    auditForm,
                    selectedOutOrderNos,
                    handleAudit,
                    submitAudit,
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>

</html>